package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.user.strategy.StrategyFactory;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private WxMaService wxMaService;

	@Autowired
	private KafkaService kafkaService;

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public Map<String, String> wxLogin(String code) {

        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            if (sessionInfo!=null) {
                String openid = sessionInfo.getOpenid();

                LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserInfo::getWxOpenId,openid);
                UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
                if(userInfo == null){
                    userInfo = new UserInfo();
                    userInfo.setWxOpenId(openid);
                    userInfo.setNickname("听友"+ IdUtil.getSnowflakeNextId());
                    userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
                    userInfo.setIsVip(0);
                    userInfoMapper.insert(userInfo);

                    // 发送Kafka异步消息，通知账户微服务新增账户记录
                    kafkaService.sendMessage(KafkaConstant.QUEUE_USER_REGISTER,userInfo.getId().toString());
                }
                String token = IdUtil.fastUUID();
                String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;

                //去除敏感信息
                UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
                redisTemplate.opsForValue().set(key,userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

                Map<String, String> mapResult = new HashMap<>();
                mapResult.put("token", token);
                return mapResult;
            }
            return null;
        } catch (Exception e) {
			log.error("[用户服务]微信登录异常：{}", e);
			throw new RuntimeException(e);
        }
    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
        return userInfoVo;
    }

    @Override
    public void updateUser(Long userId, UserInfoVo userInfoVo) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfoVo getUserInfoVoById(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
        return userInfoVo;
    }

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Override
    public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> needChackTrackIdList) {
        LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getUserId,userId);
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId,albumId);
        Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper);
        //购买了专辑
        if (count > 0) {
            HashMap<Long, Integer> map = new HashMap<>();
            for (Long trackId : needChackTrackIdList) {
                map.put(trackId,1);
            }
            return map;
        }
        //未购买专辑也未存在已购买的单曲
        LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getUserId,userId);
        userPaidTrackLambdaQueryWrapper.in(UserPaidTrack::getTrackId,needChackTrackIdList);
        List<UserPaidTrack> userPaidTracks = userPaidTrackMapper.selectList(userPaidTrackLambdaQueryWrapper);
        if (CollectionUtil.isEmpty(userPaidTracks)) {
            HashMap<Long, Integer> map = new HashMap<>();
            for (UserPaidTrack userPaidTrack : userPaidTracks) {
                map.put(userPaidTrack.getTrackId(),0);
            }
            return map;
        }
        //未购买专辑，但是存在已购买的单曲
        List<Long> list = userPaidTracks.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
        HashMap<Long, Integer> map = new HashMap<>();
        for (Long trackId : needChackTrackIdList) {
            if(list.contains(trackId)){
                map.put(trackId,1);
            }else {
                map.put(trackId,0);
            }
        }
        return map;
    }

    @Override
    public Boolean isPaidAlbum(Long userId, Long albumId) {
        LambdaQueryWrapper<UserPaidAlbum> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidAlbum::getUserId,userId);
        queryWrapper.eq(UserPaidAlbum::getAlbumId,albumId);

        Long count = userPaidAlbumMapper.selectCount(queryWrapper);
        return count > 0;
    }

    @Override
    public List<Long> findUserPaidTrackList(Long userId, Long albumId) {
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidTrack::getUserId,userId);
        queryWrapper.eq(UserPaidTrack::getAlbumId,albumId);
        List<UserPaidTrack> list = userPaidTrackMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            List<Long> ansList = list.stream().map(userPaidTrack -> userPaidTrack.getTrackId()).collect(Collectors.toList());
            return ansList;
        }
        return null;
    }

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
/*    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //1.判断购买项目类型-处理专辑
        if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(userPaidRecordVo.getItemType())) {
            //1.1 根据订单编号查询专辑购买记录
            LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getOrderNo, userPaidRecordVo.getOrderNo());
            Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper);
            if (count > 0) {
                return;
            }
            //1.2 查询到专辑购买记录为空则新增购买记录
            UserPaidAlbum userPaidAlbum = new UserPaidAlbum();
            userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
            userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));
            userPaidAlbumMapper.insert(userPaidAlbum);
        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(userPaidRecordVo.getItemType())) {
            //2.判断购买项目类型-处理声音
            //2.1 根据订单编号查询声音购买记录
            LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
            Long count = userPaidTrackMapper.selectCount(userPaidTrackLambdaQueryWrapper);
            if (count > 0) {
                return;
            }
            //2.2 查询到声音购买记录为空则新增购买记录（循环批量新增）
            //2.2.1 远程调用专辑服务-根据声音ID查询声音对象-获取声音所属专辑ID
            TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
            Long albumId = trackInfo.getAlbumId();
            //2.2.2 遍历购买项目ID集合批量新增声音购买记录
            userPaidRecordVo.getItemIdList().forEach(trackId -> {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                userPaidTrack.setAlbumId(albumId);
                userPaidTrack.setTrackId(trackId);
                userPaidTrackMapper.insert(userPaidTrack);
            });
        } else if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(userPaidRecordVo.getItemType())) {
            //3.判断购买项目类型-处理VIP会员-允许多次购买
            //3.1 新增VIP购买记录
            UserVipService userVipService = new UserVipService();
            //3.1.1 根据VIP套餐ID查询套餐信息-得到VIP会员服务月数
            Long vipConfigId = userPaidRecordVo.getItemIdList().get(0);
            VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipConfigId);
            Integer serviceMonth = vipServiceConfig.getServiceMonth();
            //3.1.2 获取用户身份，如果是VIP会员，则续费
            UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
            Integer isVip = userInfo.getIsVip();
            if (isVip.intValue() == 1 && userInfo.getVipExpireTime().after(new Date())) {
                //如果是VIP会员，则续费
                userVipService.setStartTime(userInfo.getVipExpireTime());
                //续费会员过期时间=现有会员过期时间+套餐服务月数
                userVipService.setExpireTime(DateUtil.offsetMonth(userInfo.getVipExpireTime(), serviceMonth));
            } else {
                //3.1.3 获取用户身份，如果是普通用户，则新开
                userVipService.setStartTime(new Date());
                //续费会员过期时间=现有会员过期时间+套餐服务月数
                userVipService.setExpireTime(DateUtil.offsetMonth(new Date(), serviceMonth));
            }
            //3.1.4 构建VIP购买记录对象保存
            userVipService.setUserId(userPaidRecordVo.getUserId());
            userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
            userVipServiceMapper.insert(userVipService);

            //3.2 更新用户表中VIP状态及会员过期时间
            userInfo.setIsVip(1);
            userInfo.setVipExpireTime(userVipService.getExpireTime());
            userInfoMapper.updateById(userInfo);
        }
    }*/
    @Autowired
    private StrategyFactory strategyFactory;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //从策略工厂中获取对应的策略对象
        ItemTypeStrategy strategy = strategyFactory.getStrategy(userPaidRecordVo.getItemType());
        //执行策略对象的任务
        strategy.savePaidRecord(userPaidRecordVo);
    }
}
